// @ts-check
import { defineStore } from 'pinia';

export const useBoardStore = defineStore('app', {
  state: () => {
    return {
      pageIndex: 0,
      pages: [],
      undos: [],
      redos: [],
      cachePage: null,
    }
  },
  actions: {
    // @ts-ignore

    setPage(index, page) {
      if (index >= this.pages.length) {
        // @ts-ignore
        this.pages.push(page);
      } else {
        // @ts-ignore
        this.pages[index] = page;
      }
      this.pageIndex = index;
    },
    // @ts-ignore

    addElement(ele) {
      if (this.undos.length >= 10) {
        this.undos.shift();
      }
      // @ts-ignore
      this.undos.push(this.pages[this.pageIndex].ele);
      // @ts-ignore
      this.pages[this.pageIndex].ele = ele;

      this.redos = [];
    },
    // @ts-ignore

    lastPage(func) {
      const cache = { index: this.pageIndex, undos: this.undos, redos: this.redos };
      if (this.pageIndex > 0) {
        this.pageIndex -= 1;
      }
      // @ts-ignore
      if (func) func(this.pages[this.pageIndex].ele);
      // @ts-ignore
      if (this.cachePage && this.pageIndex === this.cachePage.index) {
        // @ts-ignore
        this.undos = this.cachePage.undos;
        // @ts-ignore
        this.redos = this.cachePage.redos;
      } else {
        this.undos = [];
        this.redos = [];
      }
      // @ts-ignore
      this.cachePage = cache;
    },
    // @ts-ignore

    nextPage(func, emptyPage) {
      const cache = { index: this.pageIndex, undos: this.undos, redos: this.redos };
      if (this.pageIndex < this.pages.length - 1) {
        this.pageIndex += 1;
      } else {
        this.setPage(this.pageIndex + 1, emptyPage);
      }
      // @ts-ignore
      if (func) func(this.pages[this.pageIndex].ele)
      // @ts-ignore
      if (this.cachePage && this.pageIndex === this.cachePage.index) {
        // @ts-ignore
        this.undos = this.cachePage.undos;
        // @ts-ignore
        this.redos = this.cachePage.redos;
      } else {
        this.undos = [];
        this.redos = [];
      }
      // @ts-ignore
      this.cachePage = cache;
    },
    // @ts-ignore

    undo(func) {
      if (this.undos.length === 0) return;
      const ele = this.undos.pop();
      // @ts-ignore
      this.redos.push(this.pages[this.pageIndex].ele);
      // @ts-ignore
      this.pages[this.pageIndex].ele = ele;

      if (func) func(ele);
    },
    // @ts-ignore

    redo(func) {
      if (this.redos.length === 0) return;
      const ele = this.redos.pop();
      // @ts-ignore
      this.undos.push(this.pages[this.pageIndex].ele);
      // @ts-ignore
      this.pages[this.pageIndex].ele = ele;
      if (func) func(ele);
    },

    clear() {
      this.addElement('');
    }

  }
});